import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import './Import.css';

interface ImportProgress {
  total: number;
  processed: number;
  current: string;
  status: 'scanning' | 'importing' | 'completed' | 'error';
  error?: string;
}

/**
 * 导入页面组件
 * 负责处理文件夹选择、扫描和导入照片的流程
 */
export default function Import() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [selectedFolders, setSelectedFolders] = useState<string[]>([]);
  const [isImporting, setIsImporting] = useState(false);
  const [progress, setProgress] = useState<ImportProgress | null>(null);
  const [importHistory, setImportHistory] = useState<any[]>([]);

  useEffect(() => {
    loadImportHistory();
    
    // 处理从 URL 参数传入的文件夹
    const foldersParam = searchParams.get('folders');
    if (foldersParam) {
      try {
        const folders = JSON.parse(decodeURIComponent(foldersParam));
        if (Array.isArray(folders) && folders.length > 0) {
          setSelectedFolders(folders);
        }
      } catch (error) {
        console.error('解析文件夹参数失败:', error);
      }
    }
  }, [searchParams]);

  /**
   * 加载导入历史记录
   */
  const loadImportHistory = async () => {
    try {
      // TODO: 实现获取导入历史的 API
      // const history = await window.photosAPI.getImportHistory();
      // setImportHistory(history);
    } catch (error) {
      console.error('Failed to load import history:', error);
    }
  };

  /**
   * 选择文件夹
   */
  const handleSelectFolders = async () => {
    try {
      const result = await window.photosAPI.showOpenDialog({
        properties: ['openDirectory', 'multiSelections']
      });

      if (!result.canceled && result.filePaths.length > 0) {
        setSelectedFolders(result.filePaths);
      }
    } catch (error) {
      console.error('Failed to select folders:', error);
      await window.photosAPI.showMessageBox({
        type: 'error',
        title: '错误',
        message: '选择文件夹时发生错误',
        detail: error instanceof Error ? error.message : '未知错误'
      });
    }
  };

  /**
   * 开始导入
   */
  const handleStartImport = async () => {
    if (selectedFolders.length === 0) {
      await window.photosAPI.showMessageBox({
        type: 'warning',
        title: '提示',
        message: '请先选择要导入的文件夹'
      });
      return;
    }

    setIsImporting(true);
    setProgress({
      total: 0,
      processed: 0,
      current: '',
      status: 'scanning'
    });

    try {
      // 监听导入进度事件
      const removeProgressListener = window.photosAPI.onImportProgress((progressData) => {
        setProgress({
          total: progressData.total,
          processed: progressData.current,
          current: progressData.currentFile,
          status: progressData.status as 'scanning' | 'importing' | 'completed' | 'error'
        });
      });

      // 开始导入
      await window.photosAPI.importFolders(selectedFolders);

      // 导入完成
      setProgress(prev => prev ? { ...prev, status: 'completed' } : null);
      
      // 清理事件监听器
      removeProgressListener();
      
      // 刷新导入历史
      await loadImportHistory();

      // 显示成功消息
      await window.photosAPI.showMessageBox({
        type: 'info',
        title: '导入完成',
        message: `成功导入 ${progress?.processed || 0} 张照片`
      });

    } catch (error) {
      console.error('Import failed:', error);
      setProgress(prev => prev ? {
        ...prev,
        status: 'error',
        error: error instanceof Error ? error.message : '导入失败'
      } : null);

      await window.photosAPI.showMessageBox({
        type: 'error',
        title: '导入失败',
        message: '导入过程中发生错误',
        detail: error instanceof Error ? error.message : '未知错误'
      });
    } finally {
      setIsImporting(false);
    }
  };

  /**
   * 取消导入
   */
  const handleCancelImport = async () => {
    try {
      await window.photosAPI.cancelImport();
      setIsImporting(false);
      setProgress(null);
    } catch (error) {
      console.error('Failed to cancel import:', error);
    }
  };

  /**
   * 清除选择的文件夹
   */
  const handleClearFolders = () => {
    setSelectedFolders([]);
  };

  /**
   * 返回图库
   */
  const handleBackToLibrary = () => {
    navigate('/');
  };

  /**
   * 格式化文件大小
   */
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  /**
   * 格式化日期
   */
  const formatDate = (date: string | Date): string => {
    return new Date(date).toLocaleString('zh-CN');
  };

  return (
    <div className="import">
      {/* 工具栏 */}
      <div className="toolbar">
        <div className="toolbar-left">
          <button 
            className="btn secondary"
            onClick={handleBackToLibrary}
            disabled={isImporting}
          >
            ← 返回图库
          </button>
          <h1 className="page-title">导入照片</h1>
        </div>
        <div className="toolbar-right">
          {!isImporting && (
            <>
              <button 
                className="btn secondary"
                onClick={handleSelectFolders}
              >
                选择文件夹
              </button>
              <button 
                className="btn primary"
                onClick={handleStartImport}
                disabled={selectedFolders.length === 0}
              >
                开始导入
              </button>
            </>
          )}
          {isImporting && (
            <button 
              className="btn secondary"
              onClick={handleCancelImport}
            >
              取消导入
            </button>
          )}
        </div>
      </div>

      <div className="import-content">
        {/* 文件夹选择区域 */}
        {!isImporting && (
          <div className="folder-selection">
            <div className="section-header">
              <h2>选择要导入的文件夹</h2>
              <p>选择包含照片的文件夹，系统会自动扫描所有子文件夹中的图片文件</p>
            </div>

            {selectedFolders.length === 0 ? (
              <div className="empty-selection">
                <div className="empty-selection-icon">📁</div>
                <h3>未选择文件夹</h3>
                <p>点击"选择文件夹"按钮来选择要导入的文件夹</p>
                <button className="btn primary" onClick={handleSelectFolders}>
                  选择文件夹
                </button>
              </div>
            ) : (
              <div className="selected-folders">
                <div className="folders-header">
                  <h3>已选择 {selectedFolders.length} 个文件夹</h3>
                  <button className="btn secondary small" onClick={handleClearFolders}>
                    清除选择
                  </button>
                </div>
                <div className="folders-list">
                  {selectedFolders.map((folder, index) => (
                    <div key={index} className="folder-item">
                      <div className="folder-icon">📁</div>
                      <div className="folder-info">
                        <div className="folder-name">{folder.split('/').pop()}</div>
                        <div className="folder-path">{folder}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* 导入进度区域 */}
        {isImporting && progress && (
          <div className="import-progress">
            <div className="progress-header">
              <h2>
                {progress.status === 'scanning' && '正在扫描文件...'}
                {progress.status === 'importing' && '正在导入照片...'}
                {progress.status === 'completed' && '导入完成'}
                {progress.status === 'error' && '导入失败'}
              </h2>
            </div>

            <div className="progress-content">
              {progress.status !== 'error' && (
                <>
                  <div className="progress-bar">
                    <div 
                      className="progress-fill"
                      style={{ 
                        width: progress.total > 0 
                          ? `${(progress.processed / progress.total) * 100}%` 
                          : '0%' 
                      }}
                    />
                  </div>
                  
                  <div className="progress-stats">
                    <div className="progress-numbers">
                      {progress.processed} / {progress.total}
                    </div>
                    <div className="progress-percentage">
                      {progress.total > 0 
                        ? Math.round((progress.processed / progress.total) * 100)
                        : 0}%
                    </div>
                  </div>

                  {progress.current && (
                    <div className="current-file">
                      正在处理: {progress.current}
                    </div>
                  )}
                </>
              )}

              {progress.status === 'error' && progress.error && (
                <div className="error-message">
                  <div className="error-icon">❌</div>
                  <div className="error-text">
                    <h3>导入失败</h3>
                    <p>{progress.error}</p>
                  </div>
                </div>
              )}

              {progress.status === 'completed' && (
                <div className="success-message">
                  <div className="success-icon">✅</div>
                  <div className="success-text">
                    <h3>导入完成</h3>
                    <p>成功导入 {progress.processed} 张照片</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}

        {/* 导入历史 */}
        {!isImporting && importHistory.length > 0 && (
          <div className="import-history">
            <div className="section-header">
              <h2>导入历史</h2>
              <p>最近的导入记录</p>
            </div>
            
            <div className="history-list">
              {importHistory.map((record, index) => (
                <div key={index} className="history-item">
                  <div className="history-info">
                    <div className="history-date">
                      {formatDate(record.createdAt)}
                    </div>
                    <div className="history-details">
                      导入了 {record.photoCount} 张照片
                      {record.folderPath && (
                        <span className="history-path">
                          来自: {record.folderPath}
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="history-status">
                    {record.status === 'completed' && (
                      <span className="status-badge success">完成</span>
                    )}
                    {record.status === 'failed' && (
                      <span className="status-badge error">失败</span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}